package com.anychart.flashPrintFix {
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.external.ExternalInterface;
	import flash.geom.Matrix;
	import flash.utils.getDefinitionByName;
	
	import mx.graphics.codec.PNGEncoder;
	import mx.utils.Base64Encoder;
	
	public final class FlashPrintFix {
		
		public static const VERSION:String = "1.0.0";
		
		private static var _enabled:Boolean;
		private static var _printSource:DisplayObject;
		private static var _base64encoder:Base64Encoder = initBase64Encoder();
		private static var _pngEncoder:PNGEncoder = new PNGEncoder();
		
		private static var _initialized:Boolean = init();
		private static function init():Boolean {
			if (!ExternalInterface.available) throw new Error("External interface not available");
			
			_enabled = ExternalInterface.call("FlashPrintFix.needPrintFix");
			
			ExternalInterface.addCallback("updateContentForPrint", update);
			return true;
		}
		
		private static function initBase64Encoder():Base64Encoder {
			var res:Base64Encoder = new Base64Encoder();
			res.insertNewLines = false;
			return res;
		}
		
		public static function setCustomSource(printSource:DisplayObject):void {
			if (!_enabled) return;
			_printSource = printSource;
			update();
		}
		
		public static function initializeApp():void {
			var AppClass:Class = getDefinitionByName("mx.core.FlexGlobals") as Class;
			
			setCustomSource(AppClass.topLevelApplication);
		}
		
		public static function update(transparent:Boolean = true, bgColor:Number = 0xFFFFFFFF, matrix:Matrix = null):void {
			if (!_enabled) return;
			
			if (_printSource == null) 
				throw new Error("No source specified");
			
			if (!ExternalInterface.available)
				throw new Error("External Interface not available");
			
			var bitmap:BitmapData = new BitmapData(_printSource.width, _printSource.height, transparent, bgColor);
			bitmap.draw(_printSource, matrix);
			_base64encoder.reset();
			_base64encoder.encodeBytes(_pngEncoder.encode(bitmap));
			ExternalInterface.call("FlashPrintFix.setImg", ExternalInterface.objectID, _base64encoder.toString());
		}
	}
}